package com.das.mechanic_base.mvp.presenter.process;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.processsive.ProcessNewBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.mvp.contract.process.NewProcessNewContract;
import com.das.mechanic_base.utils.X3FileUtils;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class NewProcessNewPrestener extends X3BasePresenter<NewProcessNewContract.View> implements NewProcessNewContract.Presenter {
    @Override
    public void getWorkProceudreInfoByWorkBaseIdAndTechnicSn(String[] serviceBaseSnList,String technicTempletSn,long id ) {
        NetWorkHttp.getApi().getWorkProceudreInfoByWorkBaseIdAndTechnicSn(serviceBaseSnList,technicTempletSn,id)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<ProcessNewBean>() {
                    @Override
                    protected void onDone(ProcessNewBean processSnBeans) {
                        mView.setNewRecAdapter(processSnBeans);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void uploadWavAws(File wavFile,int titleIndex,String title,int imageIndex,String imageName,long workBaseId,String path,boolean isWork) {

        if (wavFile.getPath().endsWith(".mp4") || wavFile.getPath().endsWith(".mov")) {
            upLoadZipedFiles(wavFile,titleIndex,title,imageIndex,imageName,workBaseId,path,isWork,X3FileUtils.getFileLastModifiedTime(wavFile));
        }else {
            try {
                Luban.with(X3MyApp.getInstance().getApp())
                        .load(wavFile.getPath())
                        .ignoreBy(100)
                        .setTargetDir(X3FileUtils.getStoragePath(X3MyApp.getInstance().getApp(), X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH))
                        .filter(path1 -> !(TextUtils.isEmpty(wavFile.getPath()) || wavFile.getPath().toLowerCase().endsWith(".gif")))
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(File file) {
                                Log.e("up_load_","luban path =" + file.getPath());
                                upLoadZipedFiles(file,titleIndex,title,imageIndex,imageName,workBaseId,path,isWork,X3FileUtils.getFileLastModifiedTime(wavFile));
                            }

                            @Override
                            public void onError(Throwable e) {
                            }
                        }).launch();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void upLoadZipedFiles(File wavFile,int titleIndex,String title,int imageIndex,String imageName,long workBaseId,String path,boolean isWork,String createTime){
        RequestBody requestBody;

        Map<String,Object> imageMap = new HashMap<>();
        imageMap.put("createTime", createTime);
        imageMap.put("platform", Build.BRAND + " " + Build.MODEL);

        if (wavFile.getPath().endsWith(".mp4") || wavFile.getPath().endsWith(".mov")) {
            requestBody = RequestBody.create(MediaType.parse("video/*"), wavFile);

            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(wavFile.getPath());
            String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
            String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

            imageMap.put("width",width + "");
            imageMap.put("height",height + "");

        }else {
            requestBody = RequestBody.create(MediaType.parse("image/*"), wavFile);

            Bitmap bitmap = BitmapFactory.decodeFile(wavFile.getPath());
            Log.e("up_load_","BitmapFactory.decodeFile(wavFile.getPath()) =" + wavFile.getPath());
            if (bitmap != null) {
                imageMap.put("width",bitmap.getWidth() + "");
                imageMap.put("height",bitmap.getHeight() + "");
                bitmap.recycle();
            } else {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(wavFile.getPath(), options);
                    options.inSampleSize = 1;
                    options.inJustDecodeBounds = false;
                    int w = options.outWidth;
                    int h = options.outHeight;
                    imageMap.put("width", w + "");
                    imageMap.put("height", h + "");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        try {
            String filename = URLEncoder.encode(wavFile.getName(), "UTF-8");
            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String,RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "施工报告"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            imageMap.put("workBaseId",workBaseId);

            NetWorkHttp.getApi().uploadFileAwsForonstruction(map,fileBody,imageMap)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            mView.getAwsSoundIdSuccess(awsFileBean,titleIndex,title,imageIndex,imageName,path,isWork);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            mView.getAwsSoundIdSuccess(null,0,"",0,null,path,isWork);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void uploadVoiceAws(File wavFile) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("audio/*"), wavFile);
        try {
            String  filename = URLEncoder.encode(wavFile.getName(), "UTF-8");
            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String,RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "ANDROID_施工报告技师评论"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            NetWorkHttp.getApi().uploadFileAws(map,fileBody,new HashMap<>())
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            mView.getVoiceAws(true,awsFileBean);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            mView.getVoiceAws(false,null);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void saveWorkProceudreInfo(ProcessNewBean processNewBean) {
            NetWorkHttp.getApi().saveWorkProceudreInfo(processNewBean)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<Object>() {
                        @Override
                        protected void onDone(Object object) {
                            mView.saveWorkProceudreInfo();
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
    }


}
